<style scoped lang="scss">

</style>
<template>
  <div class="app-container">
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关 键 字">
              <el-input style="width: 95%" v-model="searchObj.keyword" placeholder="用户名/姓名/手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="createTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="margin-right: 10px;width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" icon="el-icon-search" size="mini"  @click="fetchData()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
        </el-row>
      </el-form>
    </div>
    <div class="tools-div" >
      <el-button type="success" icon="el-icon-plus" size="mini" @click="add(null)">
        添加
      </el-button>

      <el-button type="success" icon="el-icon-plus" size="mini" @click="deleteRole">
        批量删除
      </el-button>
      <el-dialog title="添加/修改" :visible.sync="dialogFormVisible">
        <el-form :model="userObject">
          <el-form-item label="用户名称" :label-width="formLabelWidth">
            <el-input v-model="userObject.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" :label-width="formLabelWidth">
            <el-input v-model="userObject.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth">
            <el-input v-model="userObject.phone"  autocomplete="off" >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
        <el-form label-width="80px">
          <el-form-item label="用户名">
            <el-input disabled :value="userObject.username"></el-input>
          </el-form-item>

          <el-form-item label="角色列表">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
              <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button type="primary" @click="assignRole" size="small">保存</el-button>
          <el-button @click="dialogRoleVisible = false" size="small">取消</el-button>
        </div>
      </el-dialog>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px"
      @selection-change="selectionchange"
    >
      <el-table-column type="selection" />
      <el-table-column
        label="序号"
        width="70"
        align="center"
      >
        <template slot-scope="scope">
          {{(page-1)*limit+scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="name" label="角色编码"/>
      <el-table-column prop="phone" label="手机" width="160"/>
      <el-table-column type="status" label="状态" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status===1"
            @change="swichStatus(scope.row)"
          >

          </el-switch>

        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"/>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button title="修改" type="primary" icon="el-icon-edit" size="mini" @click="add(scope.row)" ></el-button>
          <el-button title="分配" type="warning" icon="el-icon-baseball" size="mini" @click="editUserRole(scope.row)" ></el-button>
          <el-button title="删除" type="danger" icon="el-icon-delete" size="mini"  @click="deleteDataById(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: center"
      layout="total,prev,pager,next,jumper"
      @current-change="fetchData"
    />
  </div>
</template>

<script lang="js">
import api from '@/api/user/user'
import api2 from '@/api/user/userRole'
import th from "element-ui/src/locale/lang/th";
export default {
  data(){
    return{
      total:0,
      page:1,
      limit:3,
      searchObj:{},
      list:[],
      dialogFormVisible:false,
      userObject:{},
      createTimes:[],

        dialogRoleVisible:false,
        roleList:[],
        isIndeterminate:false,
        checkAll:false,
        userRoleIds:[]
    }
  },
  created() {
    this.fetchData()
  },
  methods:{
    fetchData(page=1){
      if(this.createTimes && this.createTimes.length ===2) {
        this.searchObj.createTimeBegin = this.createTimes[0];
        this.searchObj.createTimeEnd = this.createTimes[1];
      }
      this.page = page
      api.getPageList(this.page,this.limit,this.searchObj).then(response=>{
        this.list = response.data.records
        this.total=response.data.total
      })

    },
    resetData(){
      this.searchObj={};
      this.createTimes=[];
      this.fetchData();
    },
    editUserRole(row){
      this.userObject=row
      alert(this.userObject.id)

      api2.toAssign(this.userObject.id)
        .then((response) => {
          this.userRoleIds = response.data.userRoleIds
          this.roleList = response.data.allRoles
          this.checkAll = this.userRoleIds.length===this.roleList.length
          this.isIndeterminate = this.userRoleIds.length>0 && this.userRoleIds.length<this.roleList.length
          console.log(this.userRoleIds)
          console.log(this.roleList)


        })

        .catch((error) => {
          console.error("API 调用失败:", error);
        })

      this.dialogRoleVisible=true
    },
    handleCheckAllChange(value){
      this.userRoleIds = value ? this.roleList.map(item => item.id) : []
      this.isIndeterminate = false

    },
    handleCheckedChange (value) {
      const {userRoleIds, allRoles} = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
      this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length
    },
    assignRole(){
      let assignRoleVo={
        userId :this.userObject.id,
        userRoleIds : this.userRoleIds

      }
      api2.doAssign(assignRoleVo).then(response=>{
        this.$message.success(response.message||'分配成功')
        this.dialogRoleVisible=false
        this.fetchData(this.page)

      })}
    ,
    add(row){
      this.dialogFormVisible=true

      if (row==null){
        this.userObject={}
      }else{
        this.userObject=row
      }
    },
    swichStatus(row){
      this.userObject.id=row.id
      this.userObject.status=row.status
      api.updateStatus(this.userObject).then(response=>{
        this.userObject.status===1?0:1
        this.$message({
          type:'success',
          message:'状态更新成功'
        })
        this.fetchData()
      })
    },
    editUser(){
      if (this.userObject.id==null){
        api.addUser(this.userObject).then(response=> {
          this.$message({
            type:'success',
            message:'添加成功'
          })
          this.dialogFormVisible=false
          this.fetchData()
        })
      }else{
        api.updateUser(this.userObject).then(response=> {
          this.$message({
            type:'success',
            message:'更新成功'
          })
          this.dialogFormVisible=false
          this.fetchData()
        })
      }
    },
    deleteDataById(id){
      alert(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
          api.deleteByID(id).then(response=> {
            this.$message({
              type:'success',
              message:'删除成功'
            })
            this.fetchData()
          })

        }
      )
    }
  }
  }




</script>
